
#include <sys/socket.h>
#include <fcntl.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <assert.h>
#include <sstream>
#include <string>
#include "Facade.h"
#include "NetUtils.h"
#include "Threads.h"
#include "SockHandler.h"
#include "Debug.h"
#include "Helper.h"

using namespace std;

int SocketHandler :: ReadProcess(conn *c)
{ /* header_tag(char) + hash_key(unsigned) + if_reply(char) + data  */

	if(c->rbytes <= 0)
             return conn_closing;

	Facade *pR = Facade::Instance();
	Helper *p = Helper::Instance();
	int iret = ANT_CONN_ERR_CLOSE;
/*
        char s[INET6_ADDRSTRLEN];
	struct sockaddr addr;
	socklen_t  addrlen =0;
	getpeername(c->sfd,  &addr, &addrlen);
	inet_ntop(addr.sa_family, get_in_addr((struct sockaddr *)&addr), s, sizeof s);
	printf("============================== \n  %s\n ==============================", s);
*/
	iret = p->Process(c->rbuf, c->rbytes, &(c->wbuf), c->wsize, c->wbytes, (const char *)c->cIP);
        c->rbytes = 0;
	if(iret  ==  ANT_CONN_ERR_CLOSE)
		return conn_closing;
	if(iret  ==  ANT_CONN_NO_REPLY)
		return conn_read;

	if(TRANSMIT_COMPLETE == pR->GetNetWork()->write_block(c))
		return conn_read;
	return conn_closing;
}

int SocketHandler :: WriteProcess(conn *c)
{
	return conn_closing;
}

void * SocketHandler:: get_in_addr(struct sockaddr *sa)
{
        if (sa->sa_family == AF_INET) {
                return &(((struct sockaddr_in*)sa)->sin_addr);
        }
        return &(((struct sockaddr_in6*)sa)->sin6_addr);
}

